package com.jxl.service.impl;


import com.jxl.common.constant.PasswordConstant;
import com.jxl.common.constant.StatusConstant;
import com.jxl.common.result.PageResult;
import com.jxl.mapper.UserMapper;
import com.jxl.pojo.dto.UserPageQueryDTO;
import com.jxl.pojo.dto.UsersDTO;
import com.jxl.pojo.entity.Users;
import com.jxl.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据id查询用户信息
     * @return
     */
    @Override
    public Users getUsersById(Long Id) {
        Users user = userMapper.getUsersById(Id);
        user.setPasswordHash("*****");
        return user;
    }

    /**
     * 分页查询用户信息
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryUser(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<Users> page = userMapper.pageQuery(userPageQueryDTO);
        long total = page.getTotal();
        List<Users> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 新增用户信息
     * @param usersDTO
     */
    @Override
    public void saveUser(UsersDTO usersDTO) {
        Users users = new Users();

        BeanUtils.copyProperties(usersDTO, users);

        //设置账号状态，默认正常状态   1表示正常   0表示锁定
        users.setIsEnabled(StatusConstant.ENABLE);

        //设置密码，默认密码为123456
        users.setPasswordHash(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置当前记录的创建时间和修改时间
        users.setRegistrationDate(LocalDateTime.now());
        users.setAccountUpdatedAt(LocalDateTime.now());

        userMapper.insert(users);
    }

    /**
     * 修改用户信息
     * @param usersDTO
     */
    @Override
    public void updateUser(UsersDTO usersDTO) {

        Users users = new Users();
        BeanUtils.copyProperties(usersDTO,users);
        users.setAccountUpdatedAt(LocalDateTime.now());
        userMapper.update(users);
    }

    /**
     * 修改用户状态
     * @param status
     * @param id
     */
    @Override
    public void setStatusUser(Integer status, Long id) {
        Users users = new Users();
        users.setIsEnabled(status);
        users.setUserId(id);
        userMapper.update(users);
    }


}
